package cn.lanchengkeji.datafillingsystem.controller;


import cn.lanchengkeji.datafillingsystem.common.Const;
import cn.lanchengkeji.datafillingsystem.common.ResponseBean;
import cn.lanchengkeji.datafillingsystem.common.StatusCode;
import cn.lanchengkeji.datafillingsystem.entity.OperationLog;
import cn.lanchengkeji.datafillingsystem.entity.Roles;
import cn.lanchengkeji.datafillingsystem.entity.UserRole;
import cn.lanchengkeji.datafillingsystem.entity.Users;
import cn.lanchengkeji.datafillingsystem.exception.UserDuplicateException;
import cn.lanchengkeji.datafillingsystem.service.IOperationLogService;
import cn.lanchengkeji.datafillingsystem.service.IRolesService;
import cn.lanchengkeji.datafillingsystem.service.IUserRoleService;
import cn.lanchengkeji.datafillingsystem.service.IUsersService;
import cn.lanchengkeji.datafillingsystem.utils.HttpUtils;
import cn.lanchengkeji.datafillingsystem.utils.MD5Utils;
import cn.lanchengkeji.datafillingsystem.utils.Utils;
import cn.lanchengkeji.datafillingsystem.vo.ExportUserListVO;
import cn.lanchengkeji.datafillingsystem.vo.ExportWebUserListVO;
import cn.lanchengkeji.datafillingsystem.vo.UsersVO;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.google.common.cache.Cache;
import com.google.common.cache.CacheBuilder;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authz.annotation.RequiresAuthentication;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.web.bind.annotation.*;
import sun.misc.BASE64Encoder;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Date;
import java.util.List;
import java.util.concurrent.TimeUnit;

/**
 * <p>
 * 用户 前端控制器
 * </p>
 *
 * @author Yixu
 * @since 2018-11-29
 */
@Api(hidden = false, tags = {"用户 前端控制器"})
@RestController
@RequestMapping("/users")
public class UsersController extends BaseController {

    // 日志
    private static Logger logger = LoggerFactory.getLogger(UsersController.class);

    @Resource
    private IUsersService iUsersService;

    @Resource
    IUserRoleService iUserRoleService;

    @Resource
    IRolesService iRolesService;

    @Resource
    IOperationLogService iOperationLogService;

    //本地缓存
    Cache<String, String> cache = CacheBuilder.newBuilder().maximumSize(1000).expireAfterWrite(15, TimeUnit.MINUTES).build();

    /**
     * 待审核客户端用户列表
     *
     * @return
     * @throws Exception
     */
    @RequestMapping(value = "/checkList", method = RequestMethod.POST)
    public ResponseBean checkList(
            @RequestBody UsersVO usersParam,
            @RequestParam(value = "currentPage", required = false, defaultValue = "1") Integer currentPage,
            @RequestParam(value = "pageSize", required = false, defaultValue = "10") Integer pageSize
    ) throws Exception {

        // 查询全部用户（翻页查询）
        if (pageSize == 0) {
            pageSize = Integer.MAX_VALUE;
        }

        UsersVO searchUsers = new UsersVO();
        if (Utils.notEmpty(usersParam.getUserName())) {
            searchUsers.setUserName(usersParam.getUserName());
        }
        if (Utils.notEmpty(usersParam.getTel())) {
            searchUsers.setTel(usersParam.getTel());
        }
        Page<UsersVO> page = new Page(currentPage, pageSize);

        page = iUsersService.pageCheckUsers(page, searchUsers);
        return new ResponseBean(StatusCode.OK, page);
    }

    /**
     * 客户端用户审核
     */
    @ApiOperation(hidden = false, value = "用户审核", notes = "登录才能操作")
    @RequiresAuthentication
    @RequiresPermissions("userCheck:edit")
    @RequestMapping(value = "/check", method = RequestMethod.POST)
    public ResponseBean check(HttpServletRequest request, @RequestBody UsersVO usersParam) {



        // 获取登陆系统用户名，存入日志
        Integer userId = this.getLoginUser().getId();
        this.recordOperationLog(request, "通过用户审核", userId, "修改");

        Users users = new Users();
        users.setId(usersParam.getId());
        users.setCheckFlag(Const.USER_CHECK_PASS_3);
        boolean b = iUsersService.updateById(users);

        // 添加角色
        Integer roleId = usersParam.getRoleId();

        UserRole userRole = new UserRole();
        userRole.setUserId(users.getId());
        userRole.setRoleId(roleId);
        boolean saved = iUserRoleService.save(userRole);


        return new ResponseBean(StatusCode.OK, b && saved);
    }

    /**
     * 拒绝用户审核
     */
    @ApiOperation(hidden = false, value = "拒绝用户审核", notes = "登录才能操作")
    @RequiresAuthentication
    @RequiresPermissions("userCheck:edit")
    @RequestMapping(value = "/checkRefuse", method = RequestMethod.POST)
    public ResponseBean checkRefuse(HttpServletRequest request, @RequestBody UsersVO usersParam) {

        // 获取登陆系统用户名，存入日志
        Integer userId = this.getLoginUser().getId();
        this.recordOperationLog(request, "拒绝用户审核", userId, "修改");

        Users users = new Users();
        users.setId(usersParam.getId());
        users.setCheckFlag(Const.USER_CHECK_NOT_PASS_4);
        boolean b = iUsersService.updateById(users);
        return new ResponseBean(StatusCode.OK, b);
    }

    /**
     * 查看管理端用户
     *
     * @return
     * @throws Exception
     */
    @RequestMapping(value = "/selectUsers", method = RequestMethod.POST)
    @RequiresAuthentication
    @RequiresPermissions("user:view")
    public ResponseBean selectUsers(
            @RequestBody UsersVO usersParam,
            @RequestParam(value = "currentPage", required = false, defaultValue = "1") Integer currentPage,
            @RequestParam(value = "pageSize", required = false, defaultValue = "10") Integer pageSize
    ) throws Exception {

        if (Utils.notEmpty(usersParam.getId())) {
            // 查询单条用户
            UsersVO users = new UsersVO();
            users.setId(usersParam.getId());
            return new ResponseBean(StatusCode.OK, iUsersService.selectOneUsers(users));
        } else {

            // 查询全部用户（翻页查询）
            if (pageSize == 0) {
                pageSize = Integer.MAX_VALUE;
            }

            UsersVO searchUsers = new UsersVO();
            searchUsers.setDelFlag(0);
            if (Utils.notEmpty(usersParam.getUserName())) {
                searchUsers.setUserName(usersParam.getUserName());
            }
            if (Utils.notEmpty(usersParam.getTel())) {
                searchUsers.setTel(usersParam.getTel());
            }
            if (Utils.notEmpty(usersParam.getRoleId())) {
                searchUsers.setRoleId(usersParam.getRoleId());
            }
            // 角色id集合
            if (Utils.notEmpty(usersParam.getRoleIds()) && usersParam.getRoleIds().size() > 0) {// 角色id集合
                searchUsers.setRoleId(usersParam.getRoleIds().get(0));
            }

            Page<UsersVO> page = new Page(currentPage, pageSize);

            page = iUsersService.pageUsers(page, searchUsers);
            return new ResponseBean(StatusCode.OK, page);
        }
    }

    /**
     * 添加管理端用户
     *
     * @return
     * @throws Exception
     */
    @RequiresAuthentication
    @RequiresPermissions("user:create")
    @RequestMapping(value = "/insertUsers", method = RequestMethod.POST)
    public ResponseBean insertUsers(
            HttpServletRequest request,
            @RequestBody UsersVO usersParam
    ) throws Exception {

        // 获取登陆系统用户名，存入日志
        Integer userId = this.getLoginUser().getId();
        this.recordOperationLog(request, "添加管理端用户", userId, "新增");

        usersParam.setUserType(1); //管理端用户
        usersParam.setPasswd(MD5Utils.getStringMD5(usersParam.getPasswd()));// 密码
        usersParam.setDelFlag(0);
        usersParam.setCheckFlag(Const.USER_CHECK_PASS_3);
        usersParam.setCreateTime(new Date());
        boolean ret = iUsersService.insertUsers(usersParam);
        return new ResponseBean(StatusCode.OK, ret);
    }


    /**
     * 修改管理端用户
     *
     * @return
     * @throws Exception
     */
    @RequiresAuthentication
    @RequiresPermissions("user:edit")
    @RequestMapping(value = "/updateUsers", method = RequestMethod.POST)
    public ResponseBean updateUsers(HttpServletRequest request, @RequestBody UsersVO usersParam) throws Exception {

        // 获取登陆系统用户名，存入日志
        Integer userId = this.getLoginUser().getId();
        this.recordOperationLog(request, "编辑管理端用户信息", userId, "修改");

        if (Utils.notEmpty(usersParam.getId())) {

            if (Utils.notEmpty(usersParam.getNewPasswd())) {
                usersParam.setNewPasswd(MD5Utils.getStringMD5(usersParam.getNewPasswd()));
            }
            usersParam.setUpdateTime(new Date());
            return iUsersService.updateUsers(usersParam);
        } else {
            return new ResponseBean(StatusCode.NOT_FOUND, null);
        }

    }

    /**
     * 删除管理端用户
     *
     * @return
     * @throws Exception
     */
    @RequiresAuthentication
    @RequiresPermissions("user:delete")
    @RequestMapping(value = "/deleteUsers", method = RequestMethod.POST)
    public ResponseBean deleteUsers(
            HttpServletRequest request,
            @RequestBody Users usersParam) throws Exception {

        // 获取登陆系统用户名，存入日志
        Integer userId = this.getLoginUser().getId();
        this.recordOperationLog(request, "删除管理端用户", userId, "删除");

        if (Utils.notEmpty(usersParam.getId())) {
            return iUsersService.deleteUsers(usersParam);
        } else {
            return new ResponseBean(StatusCode.NOT_FOUND, null);
        }

    }

    /**
     * 重置用户密码
     *
     * @return
     * @throws Exception
     */
    @RequiresAuthentication
    @RequiresPermissions("user:edit")
    @RequestMapping(value = "/initPassword", method = RequestMethod.POST)
    public ResponseBean intiPassword(HttpServletRequest request, @RequestBody Users usersParam) throws Exception {

        // 获取登陆系统用户名，存入日志
        Users loginUser = this.getLoginUser();
        if (loginUser.getUserType() == 0) {
            this.recordOperationLog(request, "重置客户端用户密码", loginUser.getId(), "修改");
        } else if (loginUser.getUserType() == 1) {
            this.recordOperationLog(request, "重置管理端用户密码", loginUser.getId(), "修改");
        }

        if (Utils.notEmpty(usersParam.getId())) {
            usersParam.setPasswd(MD5Utils.getStringMD5("Xiangliang@123"));
            iUsersService.updateById(usersParam);
            return new ResponseBean(StatusCode.OK, "操作成功，初始密码为Xiangliang@123");
        } else {
            return new ResponseBean(StatusCode.OK_FAIL, null);
        }
    }

    /**
     * 查看客户端已审核用户
     *
     * @return
     * @throws Exception
     */
    @RequestMapping(value = "/selectWebUsers", method = RequestMethod.POST)
    @RequiresAuthentication
    @RequiresPermissions("user:view")
    public ResponseBean selectWebUsers(
            @RequestBody UsersVO usersParam,
            @RequestParam(value = "currentPage", required = false, defaultValue = "1") Integer currentPage,
            @RequestParam(value = "pageSize", required = false, defaultValue = "10") Integer pageSize) throws Exception {

        UsersVO searchUsers = new UsersVO();
        searchUsers.setDelFlag(0);
        if (Utils.notEmpty(usersParam.getUserName())) {
            searchUsers.setUserName(usersParam.getUserName());
        }
        if (Utils.notEmpty(usersParam.getTel())) {
            searchUsers.setTel(usersParam.getTel());
        }

        Page<UsersVO> page = new Page(currentPage, pageSize);
        page = iUsersService.pageWebUsers(page, searchUsers);

        return new ResponseBean(StatusCode.OK, page);
    }

    /**
     * 添加客户端用户
     *
     * @return
     * @throws Exception
     */
    @RequiresAuthentication
    @RequiresPermissions("user:create")
    @RequestMapping(value = "/insertWebUsers", method = RequestMethod.POST)
    public ResponseBean insertWebUsers(
            HttpServletRequest request,
            @RequestBody UsersVO usersParam) throws Exception {

        if (null == usersParam.getSubjectList()) {
            return new ResponseBean(StatusCode.IS_NULL, null);
        }

        // 获取登陆系统用户名，存入日志
        Integer userId = this.getLoginUser().getId();
        this.recordOperationLog(request, "添加客户端用户", userId, "新增");

        usersParam.setUserType(0); //管理端用户
        usersParam.setPasswd(MD5Utils.getStringMD5(usersParam.getPasswd()));// 密码
        usersParam.setDelFlag(0);
        usersParam.setCheckFlag(Const.USER_CHECK_PASS_3);
        usersParam.setCreateTime(new Date());

        List<Users> searchUsers;

        // 判断用户名是否重复
        if (Utils.notEmpty(usersParam.getUserName())) {
            QueryWrapper<Users> condition = new QueryWrapper<>();
            condition.eq(Users.USER_NAME, usersParam.getUserName());
            searchUsers = iUsersService.list(condition);
            if (searchUsers.size() > 0) {
                throw new UserDuplicateException();
            }
        }
        // 添加用户
        boolean createUserFlag = iUsersService.save(usersParam);


        return new ResponseBean(StatusCode.OK, createUserFlag);
    }

    /**
     * 修改客户端已审核用户
     *
     * @return
     * @throws Exception
     */
    @RequiresAuthentication
    @RequiresPermissions("user:edit")
    @RequestMapping(value = "/updateWebUsers", method = RequestMethod.POST)
    public ResponseBean updateWebUsers(HttpServletRequest request, @RequestBody UsersVO usersParam) throws Exception {

        if (null == usersParam.getSubjectList()) {
            return new ResponseBean(StatusCode.IS_NULL, null);
        }

        // 获取登陆系统用户名，存入日志
        Integer userId = this.getLoginUser().getId();
        this.recordOperationLog(request, "编辑客户端用户信息", userId, "修改");

        if (Utils.notEmpty(usersParam.getId())) {

            if (Utils.notEmpty(usersParam.getNewPasswd())) {
                usersParam.setNewPasswd(MD5Utils.getStringMD5(usersParam.getNewPasswd()));
            }
            if (Utils.notEmpty(usersParam.getOldPasswd())) {
                usersParam.setOldPasswd(MD5Utils.getStringMD5(usersParam.getOldPasswd()));
            }
            usersParam.setUpdateTime(new Date());
            ResponseBean responseBean = iUsersService.updateWebUsers(usersParam);


            return responseBean;
        } else {
            return new ResponseBean(StatusCode.NOT_FOUND, null);
        }

    }

    /**
     * 删除客户端已审核用户
     *
     * @return
     * @throws Exception
     */
    @RequiresAuthentication
    @RequiresPermissions("user:delete")
    @RequestMapping(value = "/deleteWebUsers", method = RequestMethod.POST)
    public ResponseBean deleteWebUsers(
            HttpServletRequest request,
            @RequestBody Users usersParam) throws Exception {

        // 获取登陆系统用户名，存入日志
        Integer userId = this.getLoginUser().getId();
        this.recordOperationLog(request, "删除客户端用户", userId, "删除");

        if (Utils.notEmpty(usersParam.getId())) {

            return iUsersService.deleteUsers(usersParam);
        } else {
            return new ResponseBean(StatusCode.NOT_FOUND, null);
        }

    }


    @ApiOperation(value = "用户修改密码", notes = "登陆才能操作")
    @RequiresAuthentication
    @RequiresPermissions("user:view")
    @RequestMapping("/updateUserPassword")
    public ResponseBean updateUserPassword(HttpServletRequest request, @RequestBody UsersVO usersPassword) {
        Object obj = SecurityUtils.getSubject().getPrincipal();
        logger.debug((String) obj);
        if (Utils.notEmpty(usersPassword.getNewPasswd()) && Utils.notEmpty(usersPassword.getOldPasswd())) {
            String userName = obj.toString();
            Users user = iUsersService.getUserByName(userName);

            if (user.getPasswd().equals(usersPassword.getOldPasswd())) {
                user.setPasswd(usersPassword.getNewPasswd());
                QueryWrapper<Users> updateByCondition = new QueryWrapper<>();
                updateByCondition.eq(Users.ID, user.getId());
                boolean update = iUsersService.update(user, updateByCondition);
                if (update) {

                    // 记录管理端日志
                    if (user.getUserType() == 1) {
                        OperationLog operationLog = new OperationLog();
                        operationLog.setOperationUserId(user.getId());
                        operationLog.setOperationUserName(user.getUserName());
                        operationLog.setOperationRealName(user.getRealName());
                        operationLog.setOperationUserOrganization(user.getOrganization());
                        operationLog.setOperationDate(new Date());
                        operationLog.setRemoteIp(HttpUtils.getIPAddress(request));
                        operationLog.setOperationEvent("导航");
                        operationLog.setOperationType("修改");
                        // 只有二级菜单下的操作才记录日志
                        operationLog.setOperationMenu("修改密码");
                        iOperationLogService.save(operationLog);
                    }
                    return new ResponseBean(StatusCode.OK, null);
                } else {
                    return new ResponseBean(StatusCode.OK_FAIL, null);
                }
            } else {
                return new ResponseBean(StatusCode.USER_PWD_ERROR, null);
            }
        } else {
            return new ResponseBean(StatusCode.NOT_FOUND, null);
        }
    }

    /**
     * 修改个人用户信息
     *
     * @param usersVO
     * @return
     */
    @RequestMapping(value = "/updateUserInfo", method = RequestMethod.POST)
    @RequiresAuthentication
    public ResponseBean updateUserInfo(@RequestBody UsersVO usersVO) {
        Integer userId = this.getLoginUser().getId();
        usersVO.setId(userId);

        List<Users> searchUsers;
        // 判断除本身外用户名是否重复
        if (Utils.notEmpty(usersVO.getUserName())) {
            QueryWrapper<Users> condition = new QueryWrapper<>();
            condition.eq(Users.USER_NAME, usersVO.getUserName()).ne(Users.ID, usersVO.getId());
            searchUsers = iUsersService.list(condition);
            if (searchUsers.size() > 0) {
                return new ResponseBean(StatusCode.USER_NAME_REPEAT, null);
            }
        }
        usersVO.setUpdateTime(new Date());
        boolean ret = iUsersService.updateById(usersVO);
        return new ResponseBean(StatusCode.OK, ret);
    }

//    /**
//     * 找回密码 发送邮件
//     *
//     * @param usersVO
//     * @return
//     */
//    @RequestMapping(value = "/retrievePassword", method = RequestMethod.POST)
//    public ResponseBean retrievePassword(@RequestBody UsersVO usersVO) {
//        String userName = usersVO.getUserName();
//        QueryWrapper<Users> queryWrapper = new QueryWrapper<>();
//        queryWrapper.select(Users.USER_NAME, Users.MAIL);
//        queryWrapper.eq(Users.USER_NAME, userName);
//        queryWrapper.eq(Users.DEL_FLAG, Const.DEL_FLAG_NO);
//        Users one = iUsersService.getOne(queryWrapper);
//        if (Utils.isEmpty(one)) {
//            return new ResponseBean(StatusCode.USER_NOT_FOUND, null);
//        }
//
//        // 创建验证码
//        char[] codeSequence = {'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'M', 'N', 'P', 'Q', 'R',
//                'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z', '2', '3', '4', '5', '6', '7', '8', '9'};
//        Random random = new Random();
//        StringBuffer randomCode = new StringBuffer();
//        // 随机产生验证码字符
//        for (int i = 0; i < 4; i++) {
//            String strRand = String.valueOf(codeSequence[random.nextInt(codeSequence.length)]);
//            randomCode.append(strRand);
//        }
//        // 验证码
//        String code = randomCode.toString();
//        // 邮件模板
//        String html =
//                "<html><p>您好！<br /><br />" +
//                        "&#12288&#12288您的验证码是: <b>" + code + "</b>，如非本人操作请忽略此邮件。</p></html>";
//        MimeMessage msg = mailSender.createMimeMessage();
//        try {
//            msg.addHeader("X-Mailer", "Microsoft Outlook Express 6.00.2900.2869");
//            MimeMessageHelper helper = new MimeMessageHelper(msg, true, "utf-8");
//            helper.setFrom("桐乡市智慧农业大数据云平台" + " <" + mailProperties.getUsername() + ">");//发件人
//            helper.setTo(one.getMail());
//            helper.setSubject("找回密码");
//            helper.setText(html, true);
//        } catch (MessagingException e) {
//            throw new MileException();
//        }
//        mailSender.send(msg);
//        // 存入本地缓存Cache
//        cache.put(one.getUserName(), code);
//        return new ResponseBean(StatusCode.OK, "邮件已发送到您的邮箱！请注意查收");
//    }

    /**
     * 找回密码 修改密码
     *
     * @param usersVO
     * @return
     */
    @RequestMapping(value = "/updatePassword", method = RequestMethod.POST)
    public ResponseBean updatePassword(@RequestBody UsersVO usersVO) {

        boolean ret;
        synchronized (this) {
            // 验证缓存中的key是否存在
            if (Utils.isEmpty(cache.getIfPresent(usersVO.getUserName()))) {
                return new ResponseBean(StatusCode.OK_FAIL, null);
            }
            // 验证验证码是否匹配
            if (!(cache.getIfPresent(usersVO.getUserName()).toUpperCase().equals(usersVO.getCode().toUpperCase()))) {
                return new ResponseBean(StatusCode.V_ERR, null);
            }
            // 清除本地缓存
            cache.invalidate(usersVO.getUserName());
        }
        QueryWrapper<Users> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq(Users.USER_NAME, usersVO.getUserName());
        queryWrapper.eq(Users.DEL_FLAG, Const.DEL_FLAG_NO);
        Users userByMail = iUsersService.getOne(queryWrapper);
        userByMail.setPasswd(MD5Utils.getStringMD5(usersVO.getPasswd()));
        ret = iUsersService.updateById(userByMail);
        return new ResponseBean(StatusCode.OK, ret);
    }

    @RequiresAuthentication
    @RequestMapping("/getUserInfoByToken")
    public ResponseBean getUserInfoByToken() {
        Users loginUser = this.getLoginUser();
        UsersVO usersVO = new UsersVO();
        BeanUtils.copyProperties(loginUser, usersVO);
        QueryWrapper<UserRole> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq(UserRole.USER_ID, loginUser.getId());
        UserRole one = iUserRoleService.getOne(queryWrapper);
        if (Utils.notEmpty(one)) {
            Roles byId = iRolesService.getById(one.getRoleId());
            usersVO.setRole(byId);
        }
        return new ResponseBean(StatusCode.OK, usersVO);
    }

    /**
     * 通过账号查询邮箱接口
     *
     * @return
     * @throws Exception
     */
    @RequestMapping(value = "/getEmailByUsername", method = RequestMethod.POST)
    public ResponseBean getEmailByUsername(@RequestBody Users user) {
        // 查询单条用户
        QueryWrapper<Users> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq(Users.USER_NAME, user.getUserName());
        queryWrapper.eq(Users.DEL_FLAG, 0);
        Users one = iUsersService.getOne(queryWrapper);
        if (null == one) {
            return new ResponseBean(StatusCode.USER_NOT_FOUND, null);
        }
        String base64Str = new BASE64Encoder().encodeBuffer(one.getMail().getBytes());
        return new ResponseBean(StatusCode.OK, base64Str);
    }

    /**
     * 用户未登录状态下修改用户信息
     *
     * @return
     * @throws Exception
     */
    @RequestMapping(value = "/updateUsersByUserName", method = RequestMethod.POST)
    public ResponseBean updateUsersByUserName(@RequestBody UsersVO usersParam) throws Exception {

        if (Utils.notEmpty(usersParam.getUserName())) {
            Users userByName = iUsersService.getUserByName(usersParam.getUserName());
            if (Utils.isEmpty(userByName)) {
                return new ResponseBean(StatusCode.USER_NOT_FOUND, null);
            }
            usersParam.setId(userByName.getId());
            usersParam.setCheckFlag(Const.USER_NOT_CHECK_2);  //状态改为未审核 （之前有可能是2 审核被拒绝）
            usersParam.setUpdateTime(new Date());
            return iUsersService.updateUsersByUserName(usersParam);
        } else {
            return new ResponseBean(StatusCode.NOT_FOUND, null);
        }
    }

    /**
     * 导出管理端用户
     *
     * @return
     */
    @RequestMapping(value = "/export", method = RequestMethod.POST)
    @RequiresAuthentication
    @RequiresPermissions("user:view")
    public void exportUsers(@RequestBody Users user, HttpServletRequest request, HttpServletResponse response) {

        Integer loginUserId = this.getLoginUser().getId();
        if (user.getUserType() == 0) {

            this.recordOperationLog(request, "管理端用户列表导出", loginUserId, "查询");
            List<ExportUserListVO> list = iUsersService.getExportUserListVO();
            this.exportExcel(response, list);

        } else if (user.getUserType() == 1) {

            this.recordOperationLog(request, "客户端用户列表导出", loginUserId, "查询");
            List<ExportWebUserListVO> list = iUsersService.getExportWebUserListVO();
            this.exportExcel(response, list);
        }
    }
}
